package com.zhuizikejithreeig.cn.threeigkeji.loginfo;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.zhuizikejithreeig.cn.been.LoginBeen;
import com.zhuizikejithreeig.cn.been.NewLoginBeen;
import com.zhuizikejithreeig.cn.contect.ContectUtils;
import com.zhuizikejithreeig.cn.contect.UriContect;
import com.zhuizikejithreeig.cn.threeigkeji.BasicActivity;
import com.zhuizikejithreeig.cn.threeigkeji.CompontApplayCation;
import com.zhuizikejithreeig.cn.threeigkeji.MainActivity;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.PasswordNameSave;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;
import okhttp3.MediaType;

public class LoginActivity extends BasicActivity implements View.OnClickListener {

    private EditText mName1;
    private EditText mName2;
    private Button   mName5;
    private TextView mName3;
    private TextView mName4;
    private static final int PHOTO_PERMISS = 100;

    private boolean hasPermission = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_login);
        showBody();

        mName1 = (EditText) findViewById(R.id.name1);
        mName2 = (EditText) findViewById(R.id.name2);
        mName5 = (Button) findViewById(R.id.name5);
        mName3 = (TextView) findViewById(R.id.name3);
        mName4 = (TextView) findViewById(R.id.name4);


        mName5.setOnClickListener(this);
        mName3.setOnClickListener(this);
        mName4.setOnClickListener(this);


        //账号密码进行回显
        hasPermission();
        if (Utils.sdIsOk() || hasPermission) {
            String[] strings = PasswordNameSave.readPassword(LoginActivity.this);
            mName1.setText(strings[0]);
            mName2.setText(strings[1]);
        }


    }

    private void hasPermission() {
        PermissionGen.with(LoginActivity.this)
                .addRequestCode(PHOTO_PERMISS)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = PHOTO_PERMISS)
    public void requestPhotoSuccess() {
        //成功之后的处理
        //.......
        hasPermission = true;
    }

    @PermissionFail(requestCode = PHOTO_PERMISS)
    public void requestPhotoFail() {
        //失败之后的处理，我一般是跳到设置界面
        hasPermission = false;

        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (showRequestPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            //        Uri uri = Uri.fromParts("package", context.getPackageName());
            //        intent.setData(uri);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.name5:
                String pho = mName1.getText().toString().trim();
                String paw = mName2.getText().toString().trim();
                if (pho.isEmpty()) {
                    ToastMake.showToast(getResources().getString(R.string.string51));
                    return;
                }
                if (paw.isEmpty()) {
                    ToastMake.showToast(getResources().getString(R.string.string53));
                    return;
                }
                if (pho.length() != 11) {
                    ToastMake.showToast("电话号码输入的长度有误");
                    return;
                }

                if (Utils.isMobileNO(mName1.getText().toString().trim()) || Utils.everyPaw(mName2.getText().toString().trim())) {
                    //TODO:可以进行登录

                    if (isConnected()) {
//                        logIn(pho, paw);

                        newLogin(pho,paw);
                    } else {
                        ToastMake.showToast(getResources().getString(R.string.string57));
                    }
                }
                break;
            case R.id.name3:
                startActivity(new Intent(LoginActivity.this, RegistActivity.class));
                break;
            case R.id.name4:
                startActivity(new Intent(LoginActivity.this, ForgetActivity.class));
                break;
        }
    }

    private void newLogin(final String phoneNumber, final String passWord) {
        if (phoneNumber.length() != 11) {
            ToastMake.showToast(getResources().getString(R.string.string63));
            return;
        }

        if (!Utils.isMobileNO(phoneNumber)) {
            return;
        }

        if (!Utils.everyPaw(passWord)) {
            return;
        }

        if (!Utils.sdIsOk()) {
            return;
        }

        if (!hasPermission) {

            hasPermission();
            return;
        }
        showProgrees(getResources().getString(R.string.string61));
        OkHttpUtils
                .post()
                .url(UriContect.LOGIN)
                .addParams("phone", phoneNumber)
                .addParams("pwd", passWord)
                .addParams("tag", "1")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMake.showToast(getResources().getString(R.string.string58));
                        hideProgree();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideProgree();

                        NewLoginBeen been = GsonUtil.parseJsonToBean(response, NewLoginBeen.class);
                        if (been == null) {
                            ToastMake.showToast(getResources().getString(R.string.string58));
                            return;
                        }
                        if (!TextUtils.equals(been.getStatus(), "200")) {
                            ToastMake.showToast(been.getMsg());
                            return;
                        } else {

                            //保存账号跟密码
                            if (Utils.sdIsOk() || hasPermission) {
                                PasswordNameSave.savePassword(LoginActivity.this, phoneNumber, passWord, true);
                            }
                            CompontApplayCation.phone = phoneNumber;
                            //本地sp保存一下
                            Utils.setString(phoneNumber, ContectUtils.PHONESAVE);
                            Utils.setString(been.getData().getUser().getId(), ContectUtils.IDSAVE);
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                            如果状态是1表示尚未完成车辆信息
                            if (TextUtils.equals("1", been.getData().getUser().getStatus()) ){
                                //如果注册了没有了注册汽车
                                startActivity(new Intent(LoginActivity.this, BasicInfoActivity.class));
                            } else if (TextUtils.equals("2", been.getData().getUser().getStatus())) {
                                //如果车辆状态是2，表示尚未扫码
                                //如果没有扫描完。进入扫描界面
                                startActivity(new Intent(LoginActivity.this, ChioceSetActivity.class));
                            } else if (TextUtils.equals("3", been.getData().getUser().getStatus())) {
                                //表示全部完成
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            } else {
                                //如果有其他的，表示再加入扫码座椅
                                startActivity(new Intent(LoginActivity.this, ChioceSetActivity.class));
                            }


                        }
                    }
                });

    }

    //进行登陆操做
//    private void logIn(final String phoneNumber, final String passWord) {
//
//        if (phoneNumber.length() != 11) {
//            ToastMake.showToast(getResources().getString(R.string.string63));
//            return;
//        }
//
//        if (!Utils.isMobileNO(phoneNumber)) {
//            return;
//        }
//
//        if (!Utils.everyPaw(passWord)) {
//            return;
//        }
//
//        if (!Utils.sdIsOk()) {
//            return;
//        }
//
//        if (!hasPermission) {
//
//            hasPermission();
//            return;
//        }
//
//        HashMap<String, String> map = new HashMap<>();
//        map.put("phone", phoneNumber);
//        map.put("pwd", passWord);
//
//        String json = GsonUtil.parseMapToJson(map);
//        showProgrees(getResources().getString(R.string.string61));
//        OkHttpUtils
//                .postString()
//                .url(UriContect.LOGIN)
//                .content(json)
//                .mediaType(MediaType.parse("application/json; charset=utf-8"))
//                .build()
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                        ToastMake.showToast(getResources().getString(R.string.string58));
//                        hideProgree();
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        hideProgree();
//                        LoginBeen been = GsonUtil.parseJsonToBean(response, LoginBeen.class);
//                        if (been == null) {
//                            ToastMake.showToast(getResources().getString(R.string.string58));
//                            return;
//                        }
//                        if (!TextUtils.equals(been.getStatus(), "1")) {
//                            ToastMake.showToast(been.getMsg());
//                            return;
//                        } else {
//                            ToastMake.showToast(been.getMsg());
//                            //保存账号跟密码
//                            if (Utils.sdIsOk() || hasPermission) {
//                                PasswordNameSave.savePassword(LoginActivity.this, phoneNumber, passWord, true);
//                            }
//                            CompontApplayCation.phone = phoneNumber;
//                            //本地sp保存一下
//                            Utils.setString(phoneNumber);
//
//                            //如果状态是1表示尚未完成车辆信息
//                            if (TextUtils.equals("1", been.getData().getStatus())) {
//                                //如果注册了没有了注册汽车
//                                startActivity(new Intent(LoginActivity.this, BasicInfoActivity.class));
//                            } else if (TextUtils.equals("2", been.getData().getStatus())) {
//                                //如果车辆状态是2，表示尚未扫码
//                                //如果没有扫描完。进入扫描界面
//                                startActivity(new Intent(LoginActivity.this, ChioceSetActivity.class));
//                            } else if (TextUtils.equals("3", been.getData().getStatus())) {
//                                //表示全部完成
//                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                            } else {
//                                //如果有其他的，表示再加入扫码座椅
//                                startActivity(new Intent(LoginActivity.this, ChioceSetActivity.class));
//                            }
//
//
//                        }
//                    }
//                });
//    }


}
